import React from 'react'
import { increment, decrement, fetchCount, fetchCountAdd } from '../storeThunk/counterSlice'
import { useSelector, useDispatch } from "react-redux"

function TestThunk() {
  const counter = useSelector(state => state.counter)
  const dispatch = useDispatch()

  // 接收返回值
  // 不加unwrap()，返回值跟"counter/fetchCount/fulfilled"或者"counter/fetchCount/rejected"的action一致
  // 使用 unwrap() 获取 payload 或抛出错误，帮助判断异步 action 是否成功
  // 我试了一下，不加 unwrap，await不太认识好像
  const handleFetchCount = async () => {
    try {
      const res = await dispatch(fetchCount(5)).unwrap()
      console.log('Fetch count result:', res)
    } catch (error) {
      console.error('Error fetching count:', error)
    }
  }

  return (
    <div>
      <h2>Counter: {counter.value}</h2>
      <button onClick={() => dispatch(increment())}>+1</button>
      <button onClick={() => dispatch(decrement())}>-1</button>
      {/* <button onClick={() => dispatch(fetchCount(5))}>模拟请求</button> */}
      <button onClick={handleFetchCount}>模拟请求</button>
      <button onClick={() => dispatch(fetchCountAdd())}>模拟请求+1</button>
    </div>
  )
}

export default TestThunk
